package com.zut.chat.config;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import redis.embedded.RedisServer;

import java.io.IOException;

/**
 * 内嵌Redis配置类（仅用于开发环境）
 */
@Slf4j
@Configuration
@Profile("embedded-redis") //
public class EmbeddedRedisConfig {

    @Value("${spring.redis.port:6379}")
    private int redisPort;

    private RedisServer redisServer;

    @PostConstruct
    public void startRedis() throws IOException {
        try {
            redisServer = RedisServer.builder()
                    .port(redisPort)
                    .setting("maxmemory 64M")
                    .build();
            redisServer.start();
            log.info("内嵌Redis服务器启动成功，端口: {}", redisPort);
        } catch (Exception e) {
            log.warn("内嵌Redis启动失败，可能已有Redis实例运行: {}", e.getMessage());
        }
    }

    @PreDestroy
    public void stopRedis() {
        if (redisServer != null && redisServer.isActive()) {
            redisServer.stop();
            log.info("内嵌Redis服务器已停止");
        }
    }
}
